package io.github.quickmsg.common.integrate.topic;
/**
 * @author Zander.Wu
 */
public enum TopicFilterType {
    /**
     * 默认 TopicFilter
     */
    NONE ,
    /**
     * $queue/ 为前缀的共享订阅
     */
    QUEUE ,

    /**
     * $share/{group-name}/ 为前缀的分组订阅
     */
    SHARE;
    /**
     * 共享订阅的topic前缀
     */
    public static final String SHARE_QUEUE_PREFIX = "$queue/";
    /**
     * 分组订阅的topic前缀
     */
    public static final String SHARE_GROUP_PREFIX = "$share/";

    /**
     * 获取 topicFilter 类型
     *
     * @param topicFilter topicFilter
     * @return TopicFilterType
     */
    public static TopicFilterType getType(String topicFilter) {
        if (topicFilter.startsWith(TopicFilterType.SHARE_QUEUE_PREFIX)) {
            return TopicFilterType.QUEUE;
        } else if (topicFilter.startsWith(TopicFilterType.SHARE_GROUP_PREFIX)) {
            return TopicFilterType.SHARE;
        } else {
            return TopicFilterType.NONE;
        }
    }
    /**
     * 读取共享订阅的分组名
     *
     * @param topicFilter topicFilter
     * @return 共享订阅分组名
     */
    public static String getShareGroupName(String topicFilter) {
        int prefixLength = TopicFilterType.SHARE_GROUP_PREFIX.length();
        int topicFilterLength = topicFilter.length();
        for (int i = prefixLength; i < topicFilterLength; i++) {
            char ch = topicFilter.charAt(i);
            if ('/' == ch) {
                return topicFilter.substring(prefixLength, i);
            }
        }
        throw new IllegalArgumentException("Share subscription topicFilter: " + topicFilter + " not conform to the $share/<group-name>/xxx");
    }
}
